package dragon.tagext.sys.role;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.BodyTagSupport;

import dragon.core.db.DML;
import dragon.core.system.po.SysUserGroup;
import dragon.core.util.GlobalParameter;
import dragon.core.util.StringUtils;

@SuppressWarnings("serial")
public class Role extends BodyTagSupport {

	/**
	 * 系统中所有的用户组
	 */
	private static Map<String, String> allUserGroups = new HashMap<String, String>();

	/**
	 * 用户组代码，多个以英文逗号分隔
	 */
	private String rolekey;

	@SuppressWarnings("unchecked")
	@Override
	public int doStartTag() throws JspException {

		if (!StringUtils.isEmpty(rolekey)) {

			HttpServletRequest request = (HttpServletRequest) pageContext.getRequest();

			// 访问页面需要拥有的用户组(代码)
			String[] roles = rolekey.trim().split(",");

			// 判断用户是否拥有访问资源的权限
			boolean hasRight = false;// 是否有权限访问资源
			Map<String, Object> userGroups = (Map<String, Object>) request.getSession().getAttribute(GlobalParameter.UserGroups);
			if (userGroups != null) {
				for (String role : roles) {
					if (userGroups.containsKey(role)) {
						hasRight = true;
						break;
					}
				}
			}
			userGroups = null;

			try {
				// 没有权限访问，跳转到通知页面
				if (!hasRight) {

					// 查询访问资源需要拥有的用户组
					StringBuilder needRoles = new StringBuilder();
					for (String role : roles) {
						if (!allUserGroups.containsKey(role)) {
							// 缓存中不存在用户组，需要查询数据库
							List<Map<String, Object>> tempList = DML.query("select name from " + SysUserGroup.tableName + " where alias='" + role + "'");
							if (tempList.size() == 1) {
								allUserGroups.put(role, tempList.get(0).get("NAME").toString());
							}
							tempList = null;
						}
						needRoles.append(allUserGroups.get(role)).append(",");
					}
					String roleStr = needRoles.toString();
					needRoles = null;
					if (roleStr.length() > 0) {
						roleStr = roleStr.substring(0, roleStr.length() - 1);
					}
					request.setAttribute("roles", roleStr);

					HttpServletResponse response = (HttpServletResponse) pageContext.getResponse();
					request.getRequestDispatcher("/roles.jsp").forward(request, response);
				}

			} catch (Exception e) {
				throw new JspException(e);
			}
		}

		return EVAL_BODY_INCLUDE;
	}

	public void setRolekey(String rolekey) {
		this.rolekey = rolekey;
	}

}
